<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'

interface VideoInfo {
  playUrl?: string
  cover?: {
    blurred?: string
    detail?: string
  }
  title?: string
}

const props = defineProps<{
  videoInfo?: VideoInfo | null
}>()

const emit = defineEmits<{
  'play-start': []
  'play-complete': []
  'toggle-header': []
}>()

// 数据处理和状态
const videoRef = ref<HTMLVideoElement>()
const isPlaying = ref(false)
const isEnded = ref(false)
const showControls = ref(true)
const currentTime = ref(0)
const duration = ref(0)
const isMuted = ref(true) // 默认静音

let hideControlsTimer: number | null = null

const progressPercent = computed(() => {
  if (duration.value === 0) return 0
  return (currentTime.value / duration.value) * 100
})

// 播放/暂停
const togglePlay = () => {
  if (!videoRef.value) return
  if (isPlaying.value) {
    videoRef.value.pause()
  } else {
    videoRef.value.play()
  }
}

// 切换静音
const toggleMute = () => {
  if (!videoRef.value) return
  isMuted.value = !isMuted.value
  videoRef.value.muted = isMuted.value
  console.log('静音状态:', isMuted.value)
}

// 处理封面点击
const handleCoverClick = () => {
  if (videoRef.value) {
    videoRef.value.muted = true
    isMuted.value = true
    videoRef.value.play()
  }
}

// 重新播放
const replay = () => {
  if (videoRef.value) {
    isEnded.value = false
    videoRef.value.currentTime = 0
    videoRef.value.play()
  }
}

// 格式化时间
const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

// 视频事件处理
const onPlay = () => {
  isPlaying.value = true
  isEnded.value = false
  emit('play-start')
}

const onPause = () => {
  isPlaying.value = false
}

const onEnded = () => {
  isPlaying.value = false
  isEnded.value = true
  emit('play-complete')
}

const onTimeUpdate = () => {
  if (videoRef.value) {
    currentTime.value = videoRef.value.currentTime
  }
}

const onLoadedMetadata = () => {
  if (videoRef.value) {
    duration.value = videoRef.value.duration
    console.log('视频时长:', formatTime(duration.value))
  }
}

// 监听视频信息变化，自动静音播放
watch(() => props.videoInfo, (newVal) => {
  if (newVal && videoRef.value) {
    videoRef.value.load()
    nextTick(() => {
      if (videoRef.value) {
        videoRef.value.muted = true
        isMuted.value = true
        videoRef.value.play().catch(err => {
          console.error('自动播放失败:', err)
        })
      }
    })
  }
}, { deep: true })

// 暴露方法和数据供外部使用
defineExpose({
  videoRef,
  isPlaying,
  isEnded,
  currentTime,
  duration,
  isMuted,
  progressPercent,
  togglePlay,
  toggleMute,
  replay,
  formatTime
})
</script>
